import tkinter as tk
from tkinter import messagebox
import pandas as pd
from datetime import datetime
import os
from tkinter import ttk
from tkinter.filedialog import askopenfilename

def show_incoming_records(text_view, root):
    '''
    当入库成功后
    将本日入库记录布局到入库页面的文本框中
    '''
    datenow = datetime.now().strftime("%Y/%m/%d")
    file_path = f"入库/{datenow}.xlsx"
    try:
        df = pd.read_excel(file_path)
        text_view.delete(1.0, tk.END)
        text_view.insert(tk.END, df.to_csv(sep='\t', na_rep='nan'))
    except FileNotFoundError:
        text_view.delete(1.0, tk.END)
        text_view.insert(tk.END, f"{datenow} 今日尚无入库记录")

def record_incoming(entry_item, entry_quantity, entry_unit, entry_handler, text_view, root):
    '''
    当按钮被点击时
    记录入库信息
    '''
    time_str = datetime.now().strftime("%H:%M:%S")
    item = entry_item.get()
    quantity = entry_quantity.get()
    unit = entry_unit.get()
    handler = entry_handler.get()

    if item and quantity and unit and handler:
        try:
            quantity = int(quantity)
            datenow = datetime.now().strftime("%Y/%m/%d")
            date = datetime.now().strftime("%Y/%m")
            os.makedirs(f"入库/{date}", exist_ok=True)
            file_path = f"入库/{datenow}.xlsx"
            
            try:
                df = pd.read_excel(file_path)
            except FileNotFoundError:
                df = pd.DataFrame(columns=["入库时间", "物品", "数量", "单位", "经办人"])
                
            new_record = pd.DataFrame({
                "入库时间": [time_str],
                "物品": [item],
                "数量": [quantity],
                "单位": [unit],
                "经办人": [handler]
            })
            df = pd.concat([df, new_record], ignore_index=True)
            df.to_excel(file_path, index=False)
            messagebox.showinfo("成功", "入库记录已保存！")
            show_incoming_records(text_view, root)
        except ValueError:
            messagebox.showerror("错误", "数量必须为整数！")
    else:
        messagebox.showerror("错误", "请输入完整信息！")
        
def incoming(root, in_tab):
    text_in_view = tk.Text(in_tab, height=15)
    text_in_view.pack(fill=tk.X, padx=5, pady=5)
    
    show_incoming_records(text_in_view, root)
    
    in_input_frame = tk.Frame(in_tab)
    in_input_frame.pack(fill=tk.X, padx=5, pady=5)

    ttk.Label(in_input_frame, text="物品:").grid(row=0, column=0)
    entry_in_item = ttk.Entry(in_input_frame)
    entry_in_item.grid(row=0, column=1, padx=5)
    
    ttk.Button(in_input_frame, text="从文件导入",
             command=lambda: import_from_excel(entry_in_item, entry_in_handler, text_in_view, root))\
             .grid(row=0, column=2, padx=5)

    ttk.Label(in_input_frame, text="数量:").grid(row=0, column=3)
    entry_in_quantity = ttk.Entry(in_input_frame, width=6)
    entry_in_quantity.grid(row=0, column=4, padx=5)

    ttk.Label(in_input_frame, text="单位:").grid(row=0, column=5)
    entry_in_unit = ttk.Entry(in_input_frame, width=6)
    entry_in_unit.grid(row=0, column=6, padx=5)

    ttk.Label(in_input_frame, text="经办人:").grid(row=0, column=7)
    entry_in_handler = ttk.Entry(in_input_frame)
    entry_in_handler.grid(row=0, column=8, padx=5)

    in_button_frame = ttk.Frame(in_tab)
    in_button_frame.pack(fill=tk.X, padx=5, pady=5, expand=True)

    ttk.Button(in_button_frame, text="登记入库",
            command=lambda: (
                record_incoming(
                    entry_in_item,
                    entry_in_quantity,
                    entry_in_unit,
                    entry_in_handler,
                    text_in_view,
                    root
                )
            )).pack(side=tk.LEFT, padx=10)

    ttk.Button(in_button_frame, text="退出系统",
             command=root.destroy).pack(side=tk.RIGHT, padx=10)

def import_from_excel(entry_item, entry_handler, text_view, root):
    '''
    从Excel文件导入入库记录
    文件至少要包含'物品', '数量', '单位'等信息
    需要提前输入经办人信息
    '''
    handler = entry_handler.get()
    if not handler:
        messagebox.showerror("错误", "请先输入经办人！")
        return

    filepath = askopenfilename(filetypes=[("Excel表格", "*.xls *.xlsx")])
    if not filepath:
        messagebox.showerror("错误", "文件不存在！")
        return

    try:
        df = pd.read_excel(filepath)

        required_columns = ['物品', '数量', '单位']
        if not all(col in df.columns for col in required_columns):
            messagebox.showerror("错误", "Excel文件必须包含物品、数量、单位列!")
            return

        # 获取当前日期，格式化为年/月/日
        now = datetime.now()
        year = now.year
        month = now.month
        day = now.day
        
        # 创建目录结构
        base_dir = "入库"
        year_dir = os.path.join(base_dir, str(year))
        month_dir = os.path.join(year_dir, f"{month:02d}")
        
        os.makedirs(month_dir, exist_ok=True)
        
        # 构建文件路径
        target_file = os.path.join(month_dir, f"{day:02d}.xlsx")
        
        # 添加时间和经办人信息
        time_str = now.strftime("%H:%M:%S")
        df['入库时间'] = time_str
        df['经办人'] = handler
        
        # 确保列的顺序正确
        if '备注' in df.columns:
            df = df[['入库时间', '物品', '数量', '单位', '经办人', '备注']]
        else:
            df = df[['入库时间', '物品', '数量', '单位', '经办人']]

        # 合并现有数据（如果存在）
        if os.path.exists(target_file):
            try:
                existing_df = pd.read_excel(target_file)
                combined_df = pd.concat([existing_df, df], ignore_index=True)
            except Exception:
                # 如果读取现有文件失败，则只使用新数据
                combined_df = df
        else:
            combined_df = df
        
        # 保存到Excel文件
        combined_df.to_excel(target_file, index=False)
        messagebox.showinfo("成功", f"成功导入{len(df)}条记录！")
        show_incoming_records(text_view, root)
        
    except Exception as e:
        messagebox.showerror("错误", f"文件读取失败: {str(e)}")